<template>
  <el-tabs :tab-position="tabPosition" style="height: 900px;">
    <el-tab-pane v-for="type in types" :key="type" :label="type">
      <!-- 搜索栏 -->
      <div class="search-bar" style="display: flex; justify-content: center; margin-bottom: 20px;">
        <el-input :placeholder="'请输入你想搜索的 ' + type + ' 乐谱...'" v-model="queryStr[type]" class="input-with-select"
          style="width: 70%; max-width: 400px;">
          <template #append>
            <el-button class="button" type="success" @click="queryInfo(type)">查询</el-button>
          </template>
        </el-input>
      </div>
      <!-- 乐谱展示代码 -->
      <el-row gutter="30">
        <el-col v-for="(item, index) in filteredList[type]" :key="index" :span="5">
          <div class="notation-out">
            <img :src="'http://localhost:8080/images/upload/' + item.cover_image" class="card-img-top" alt="乐谱封面"
              @click="goToNotationDetail(item)">
            <div class="notation-info">
              <h4 class="card-title">{{ item.name }}</h4>
              <p class="authors">作词：{{ item.author_word }} | 作曲：{{ item.author_song }}
        <el-button class="more-button" type="text" @click="goToNotationDetail(item)">详情</el-button></p>
            </div>
          </div>
        </el-col>
      </el-row>


    </el-tab-pane>
  </el-tabs>

  <el-pagination
  :current-page.sync="currentPage"
  :page-size="pageSize"
  :total="totalItems"
  layout="prev, pager, next"
  @current-change="handlePageChange"
/>

</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      currentPage: 1,
      pageSize: 12,
      totalItems: 20,
      types: [
        '全部',
        '传统音乐类',
        '新国风流行类',
        '戏曲融合类',
        '主题文化类',
        '地域特色类'
      ],
      filteredList: {},
      imageList: [],
      queryStr: {},
      tabPosition: 'right',
    };
  },
  computed: {
    totalPages() {
      return Math.ceil(this.totalItems / this.pageSize);
    }
  },
  created() {
    this.fetchNotationData();
    this.initQueryStrAndFilteredList();
  },
  methods: {
    handlePageChange(page) {
      this.currentPage = page;
      this.updateFilteredList();
    },



    goToNotationDetail(item) {
    // 调用后端接口增加浏览量
    this.incrementViewCount(item.notation_id).then(() => {
      // 浏览量增加后，再进行页面跳转
      sessionStorage.setItem('notation_id', item.notation_id);
      this.$router.push({ path: '/notation/' + item.notation_id });
    }).catch(error => {
      console.error('Failed to increment view count:', error);
      // 即使增加浏览量失败，也进行页面跳转
      sessionStorage.setItem('notation_id', item.notation_id);
      this.$router.push({ path: '/notation/' + item.notation_id });
    });
  },
  incrementViewCount(notationId) {
    return axios.post(`/v1/notation/View/${notationId}`).then(response => {
      console.log('View count incremented');
      return response;
    }).catch(error => {
      console.error('Failed to increment view count:', error);
      throw error;
    });
  },


    initQueryStrAndFilteredList() {
      this.types.forEach(type => {
        this.queryStr[type] = '';
        this.filteredList[type] = [];
      });
      this.filteredList['全部'] = [];
    },
    
    fetchNotationData() {
      axios.get('/v1/notation1/').then(response => {
        this.imageList = response.data;
        this.totalItems = this.imageList.length;
        this.types.forEach(type => {
          this.filterData(type);
        });
        this.updateFilteredList();
      }).catch(error => {
        console.error('获取乐谱数据失败：', error);
      });
    },
    filterData(type) {
      if (type === '全部') {
        this.filteredList[type] = this.imageList.slice();
      } else {
        this.filteredList[type] = this.imageList.filter(item => item.type === type);
      }
    },
    queryInfo(type) {
      if (this.queryStr[type].trim().length > 0) {
        const query = this.queryStr[type].trim();
        const matched = this.imageList.filter(item => item.name.includes(query));
        this.filteredList[type] = type === '全部' ? matched : matched.filter(item => item.type === type);
      } else {
        this.filterData(type);
      }
    },
    updateFilteredList() {
      this.types.forEach(type => {
        const filteredData = type === '全部' ? this.imageList : this.imageList.filter(item => item.type === type);
        const start = (this.currentPage - 1) * this.pageSize;
        const end = this.currentPage * this.pageSize;
        this.filteredList[type] = filteredData.slice(start, end);
      });
    },
  }
};
</script>

<style>
.input-with-select {
  width: 200px;
  /* 你可以根据需要调整这个值 */
  padding: 5px;
  /* 内边距，可以根据需要调整 */
  font-size: 16px;
  /* 字体大小，可以根据需要调整 */
  border: 1px solid #ffffff;
  /* 边框样式，可以根据需要调整 */
  border-radius: 4px;
  /* 边框圆角，可以根据需要调整 */
}

.el-col {
  margin-bottom: 30px;
  /* 每张卡片底部的间距增加 */
}

.notation-out {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #fff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-radius: 10px;
  overflow: hidden;

}

.el-row {
  display: flex;
  justify-content: space-between;
  /* 平均分布卡片 */
  flex-wrap: wrap;
  /* 自动换行 */
}

.notation-cover {
  width: 100%;
  height: 200px;
  /* 固定图片的高度，确保占据卡片的上方区域 */
  object-fit: cover;
  /* 确保图片填充区域，不变形 */
}

.notation-info {
  padding: 10px;
  flex-grow: 1;
  /* 让文本区域填充剩余空间 */
  text-align: center;
}

.notation-info h4 {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-top: 10px;
}

.notation-info p {
  font-size: 14px;
  color: #777;
}


/* 鼠标悬浮特效 */
.notation-out:hover {
  transform: scale(1.03);
  /* 轻微放大 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  /* 添加阴影效果 */
}

/* 确保图片宽度和高度一致 */
.card-img-top {
  width: 100%;
  /* 图片宽度100% */
  height: 120px;
  /* 图片高度固定 */
  object-fit: cover;
  /* 裁剪图片以适应容器 */
}

.notation-item {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
}


</style>